/**
 * jusetoken middlewares
 * code by pange
 * 2017-4-7
 *
 */
/**
 * 权限认证设计思路
 *
 * 1.获取token，取出tree
 * 2.获取req.originalUrl
 * 3.处理url  去掉‘／’
 * 4.判断 3是否在1中
 */
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../../config/config');

module.exports = {
  // 权限审核中间件
  ensureAuthenticated: function ensureAuthenticated(req, res, next) {
    if (!req.header('Authorization')) {
      return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
    }
    const token = req.header('Authorization').split(' ')[1];

    let payload = null;
    try {
      payload = jwt.decode(token, config.TOKEN_SECRET);
    } catch (err) {
      return res.status(401).send({ message: err.message });
    }

    if (!payload.exp || payload.exp <= moment().unix()) {
      return res.status(401).send({ message: 'Token has expired' });
    }
    req.user = payload.user;
    next();
    //     console.log(payload.user,66666)
    //     req.user = payload.user;

    //     const tree = req.user.tree;   // 获取token 并去除tree

    //     let url = req.originalUrl; // 获取req.originalUrl

    //     url = url.replace(/\//g, ''); // 处理url  去掉‘／’

    //     if (tree.includes(url)) {
    //     // if (1) {
    //       next();
    //  } else {
    //       return res.status(401).send({ message: 'You do not have the authority' });
    //     }
  },
  // 生成jwt token
  createJWT: function createJWT(user) {

    var payload = {
      user: user,
      iat: moment().unix(),
      exp: moment().add(14, 'days').unix(),
    };

    try {
      return jwt.encode(payload, config.TOKEN_SECRET);
    } catch (error) {
      return error;
    }
    return jwt.encode(payload, config.TOKEN_SECRET);
  }
  // 增加权限认真的中间键
};
